﻿using System;
using System.Reflection;
using Phidgets;
using Coding4Fun.MissionControl.API.Models;

namespace Coding4Fun.MissionControl.API.Data
{
    public static class IRCodeWorker
    {
        public static SerializableIRCode GetSerializableIRCode(IRLearnedCode code)
        {
            SerializableIRCode sCode = new SerializableIRCode();
            sCode.BitSize = code.Code.BitCount;
            sCode.Encoding = code.CodeInfo.Encoding;
            sCode.CarrierFrequency = code.CodeInfo.CarrierFrequency;
            sCode.CodeData = code.Code.Data;
            sCode.DutyCycle = code.CodeInfo.DutyCycle;
            sCode.Gap = code.CodeInfo.Gap;
            sCode.Header = code.CodeInfo.Header;
            sCode.MinRepeat = 5;
            sCode.One = code.CodeInfo.One;
            sCode.Repeat = code.CodeInfo.Repeat;
            sCode.Trail = code.CodeInfo.Trail;
            sCode.Zero = code.CodeInfo.Zero;
            sCode.Mask = new ToggleMask()
            {
                BitSize = code.CodeInfo.ToggleMask.BitCount,
                CodeData = code.CodeInfo.ToggleMask.Data
            };

            return sCode;
        }

        internal static IRLearnedCode GetLearnedCode(SerializableIRCode serializableIRCode)
        {
            try
            {
                IRCode code = new IRCode(serializableIRCode.CodeData, serializableIRCode.BitSize);
                IRCodeInfo info = new IRCodeInfo(serializableIRCode.Encoding, serializableIRCode.BitSize, serializableIRCode.Header,
                    serializableIRCode.Zero, serializableIRCode.One, serializableIRCode.Trail, serializableIRCode.Gap, serializableIRCode.Repeat, serializableIRCode.MinRepeat,
                    serializableIRCode.Mask.CodeData, IRCodeInfo.IRCodeLength.Constant, serializableIRCode.CarrierFrequency, serializableIRCode.DutyCycle);

                object[] parameters = new object[] { code, info };
                BindingFlags flags = BindingFlags.NonPublic | BindingFlags.Instance;
                object instantType = Activator.CreateInstance(typeof(IRLearnedCode), flags, null, parameters, null);

                return (IRLearnedCode)instantType;
            }
            catch
            {
                return null;
            }
        }
    }
}
